package br.com.spring.mvc.controller;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import br.com.spring.mvc.component.SimpleComponent;
import br.com.spring.mvc.dto.SimpleDTO;
import br.com.spring.mvc.entity.Simple;
import br.com.spring.mvc.entity.infra.Message;
import br.com.spring.mvc.validator.SimpleValidator;

@Controller
@RequestMapping(value = "/simple")
public class SimpleController extends BaseController {
	
	@SuppressWarnings("unused")
	private static final Logger logger = LoggerFactory.getLogger(SimpleController.class);
	
	@Autowired
	private SimpleComponent component;
	
	@RequestMapping("/")
	public String initial(Model model){
		return "simple-tiles";
	}
	
	@RequestMapping("/dados")
	public String list(Model model){
		model.addAttribute("simples", component.list());
		return "simple-dados-tiles";
	}
	
	@SuppressWarnings("finally")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public @ResponseBody String create(@Valid @ModelAttribute SimpleDTO entity, BindingResult result) {
		try {
			clearAttributes();
			entity.validate(result);
//			component.save(entity);	
			entity.addSuccesMessage("Registro cadastrado com sucesso!");
		} catch (Exception e) {
			if(!e.getMessage().isEmpty()){addMessage(Message.getErrorMessage(e.getMessage()));}
		} finally {
			return getAttributesFromJson();		
		}		
	}

	private void validate(Simple entity, BindingResult result) {
		new SimpleValidator().validate(entity, result);
	}
	
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	public String delete(@PathVariable int id) {
		component.delete(id);
		return "simple-dados-tiles";
	}
	
	@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
	public String get(@ModelAttribute("simple") Simple simple, Model model, BindingResult result) {
		try {
			clearAttributes();
			setAttributes(model);
			validate(simple, result);
			addError(result.getAllErrors());
			addAttribute("simple", component.get(simple.getId()));
		} catch (Exception e) {
			if(!e.getMessage().isEmpty()){addMessage(Message.getErrorMessage(e.getMessage()));}			
			return "simple-dados-tiles";	
		}
		return "simple-tiles";	
	}
}
